package com.attendance.www.hr.service.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.EmployeeBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.EmployeeExtMapper;
import com.attendance.www.hr.dao.mapper.RoleExtMapper;
import com.attendance.www.hr.dao.mapper.SystemConfigureMapper;
import com.attendance.www.hr.entitys.SystemConfigure;
import com.attendance.www.hr.service.IEmployeeAbsenteeismService;
import com.attendance.www.hr.utils.MailUtils;

/**
 * 员工旷工接口
 * 
 * @author 崔棋 2020-06-29
 */
@Service
public class EmployeeAbsenteeismServiceImpl implements IEmployeeAbsenteeismService {

	@Resource
	private RoleExtMapper roleExtDao;
	@Resource
	private EmployeeExtMapper employeeExtDao;
	@Resource
	private SystemConfigureMapper systemConfigureDao;

	private static Logger log = Logger.getLogger(EmployeeAbsenteeismServiceImpl.class);
	
	/**
	 * 员工连续旷工两天以上邮件提醒
	 */
	@Override
	public void employeeAbsenteeismMail() {
		boolean absenteeismType=Boolean.parseBoolean(AppConstant.ABSENTEEISM_TYPE);
		if(!absenteeismType) {
			return;
		}
		// 查询初始化表
		SystemConfigure systemConfigure = systemConfigureDao.selectByPrimaryKey(1);
		// 获取当前日期
		Calendar now = Calendar.getInstance();
		Integer year = now.get(Calendar.YEAR);
		Integer month = now.get(Calendar.MONTH) + 1;
		//Integer month = 4;
		// 获取员工旷工两次以上数据
		List<EmployeeBean> employeeBeanList = employeeExtDao.getEmployeeAbsenteeismList(year, month);
		// 循环员工-根据岗位ID，获取N+1员工邮件，发送邮件
		for (int i = 0; i < employeeBeanList.size(); i++) {
			EmployeeBean employeeBean = employeeBeanList.get(i);
			// 邮件内容
			String text = MailUtils.toGBK(AppConstant.MAIL_ABSENTEEISM_CONTENT);
			// 替换内容格式
			text = text.replace("@a", "(" + employeeBean.getEmployeeNo() + ")" + employeeBean.getChineseName()+" "+year+"年"+month+"月")
					.replace("@b", employeeBean.getCount().toString());
			// 岗位向上递归查询岗位信息
			String roleIdStr = roleExtDao.getDeepQueryRoledID(employeeBean.getRoleId());
			if (!StringUtils.isBlank(roleIdStr)) {
				// 岗位信息，查询对应员工邮箱等信息
				List<EmployeeBean> ebList = employeeExtDao.getEmployeeAbsenteeismListByRoleId(roleIdStr);
				for (int j = 0; j < ebList.size(); j++) {
					EmployeeBean eb = ebList.get(j);
					log.info("开始发送邮件："+ eb.getEmail());
					// 发邮件
					MailUtils.send(systemConfigure, eb.getEmail(), AppConstant.MAIL_TITLE, text,
							AppConstant.MAIL_ENDING);
				}
			}
		}
	}

}
